package com.hyh.spring.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @BelongsPackage: com.hyh.spring.service
 * @ClassName PaymentService
 * @Author: hyhWTX
 * @CreateTime: 2023-04-15  13:00
 * @Description: TODO (一句话描述以下该类的功能)
 * @Version: 1.0
 */
@Service
public class PaymentService {
    /**
     * 正常访问方法
     * @param id
     * @return
     */
    public String paymentInfo_OK(Integer id){
        return "线程池："+Thread.currentThread().getName() + "：paymentInfo_OK,id："+id+"\t"+"O(∩_∩)O哈哈~";
    }

    /**
     * 超时访问，演示降级
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
            //超过3秒，出错，出的是超时的错误，有一个兜底方法，当服务不可用了之后，做服务降级，兜底方案是paymentInfo_TimeOutHandler
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
            //兜底，就是当程序用时为3秒时，符合要求，正常的服务逻辑
    })
    public String paymentInfo_TimeOut(Integer id){
        //设置服务周期，time内是符合要求的正常时间
        //设置自身调用超时时间的峰值，峰值内可以正常运行， 超过了需要有兜底的方法处理，作服务降级fallback
        int a = 10/0;//报错测试
       // int time = 5;
//        try {
//            TimeUnit.MILLISECONDS.sleep(time);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
        return "线程池："+Thread.currentThread().getName() + "：paymentInfo_TimeOut,id："+id+"\t"+"O(∩_∩)O哈哈~"+"耗时3秒钟！";
    }

    public String paymentInfo_TimeOutHandler(Integer id){
        return "线程池名字："+Thread.currentThread().getName()+"：系统繁忙或者运行错误报错，请稍后再试，id："+id+"\t"+"o(╥﹏╥)o" ;
    }

    /**
     * 配置服务熔断
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到多少后跳闸
    })
    public  String paymentCircuitBreaker(@PathVariable("id")Integer id){
        if (id<0){
            throw new RuntimeException("******id 不能负数");
        }
        String simpleUUID = IdUtil.simpleUUID();
        return "线程池："+Thread.currentThread().getName()+"O(_)O哈哈~"+"调用成功，流水号："+simpleUUID;

    }

    public String paymentCircuitBreaker_fallback(@PathVariable("id")Integer id){
        return "id 不能为负数，请稍后在试，/(ㄒoㄒ)/~~   id: " +id;
    }
}
